﻿using System;
using System.Collections.Generic;
using Common.Logging;
using Jose;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Qy.Yzrb.Helpers
{
    public static class JwtTokenHelper
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(JwtTokenHelper));
        private static readonly byte[] SecretKey = new byte[] { 26, 60, 193, 10, 161, 189, 41, 38, 130, 89, 141, 164, 45, 170, 159, 209, 62, 137, 243, 216, 191, 131, 147, 252, 32, 107, 231, 117, 37, 158, 225, 234 };

        public static string CreateJwtToken(string userId)
        {
            var payload = new Dictionary<string, object>()
            {
                {"uid", userId}
            };

            string token = Jose.JWT.Encode(payload, SecretKey, JwsAlgorithm.HS256);

            return token;
        }

        public static bool ValidateJwtToken(string token,  out string userId)
        {
            userId = "";

            try
            {
                string json = Jose.JWT.Decode(token, SecretKey);
                var jo = JsonConvert.DeserializeObject<JObject>(json);

                userId = jo["uid"].ToString();

                return true;
            }
            catch (Exception ex)
            {
                Logger.InfoFormat("错误的令牌\r\ntoken:{0}\r\nerror:{1}", token, JsonConvert.SerializeObject(ex));
                return false;
            }
        }
    }
}